package com.tbit.uqbike.client.service.impl;

import com.tbit.uqbike.client.dao.core.UserToAgentDao;
import com.tbit.uqbike.client.pojo.UserToAgent;
import com.tbit.uqbike.client.service.UserToAgentService;
import com.tbit.uqbike.client.util.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: chen
 * @Description:
 * @Date: 创建于 9:58 2022/11/24
 */
@Service
public class UserToAgentServiceImpl implements UserToAgentService {

    @Autowired
    private UserToAgentDao userToAgentDao;

    @Override
    public void insert(Integer userId, Integer accountId) {
        UserToAgent userToAgentDb = getByAccountId(userId);
        Integer firstId = accountId;
        //是否是新增用户,加一堆if else的原因是大部分用户都在同一个区域骑行，防止多次重复查询数据库
        boolean flag = false;
        if (userToAgentDb != null) {
            firstId = userToAgentDb.getAccountId();
            if (accountId.equals(userToAgentDb.getAccountId())) {
                flag = false;
            } else {
                //查询数据库中是否有已有绑定关系
                if (!userToAgentDao.checkBind(userId, accountId)) {
                    flag = true;
                }
            }
        } else {
            flag = true;
        }
        UserToAgent userToAgent = new UserToAgent();
        userToAgent.setUserId(userId);
        userToAgent.setAccountId(accountId);
        userToAgent.setUpdateDt(DateTimeUtil.getNowTime());
        userToAgent.setFirstId(firstId);
        userToAgentDao.insert(userToAgent);
        if (flag) {
            //插入区域新增用户
            userToAgentDao.insertBindTime(userToAgent);
        }
    }

    @Override
    public UserToAgent getByUserId(Integer userId) {
        return userToAgentDao.getByUserId(userId);
    }

    @Override
    public UserToAgent getByAccountId(Integer userId) {
        return userToAgentDao.getByAccountId(userId);
    }
}
